
#include "stopwatch.hpp"
#include <sys/time.h>
#include <cassert>

void stopwatch::start()
{
	if(rng || (data == 0))
		return;
	gettimeofday(&((timeval*)data)[0],0);
	rng = true;
}

void stopwatch::stop()
{
	if(!rng || (data == 0))
		return;
	gettimeofday(&((timeval*)data)[1],0);
	rng = false;
	calc_diff();
}

void stopwatch::calc_diff()
{
	timeval & beg = ((timeval*)data)[0];
	timeval & end = ((timeval*)data)[1];
	curr = (end.tv_sec*100000LL+end.tv_usec) - (beg.tv_sec*100000LL+beg.tv_usec);
}

const unsigned long long int stopwatch::read()
{
	if(!rng) return curr;
	timeval now;
	timeval & beg = ((timeval*)data)[0];
	gettimeofday(&now,0);
	return (now.tv_sec*100000LL+now.tv_usec) - (beg.tv_sec*100000LL+beg.tv_usec);
}

void stopwatch::initialize_data()
{
	assert(data == 0);
	data = new timeval[2];
}

stopwatch::~stopwatch()
{
	if(data)
	{
		delete [] (timeval*)(data);
		data = 0;
	}
}

